﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Services;
using System.Web.Services;
using System.Configuration;

using ZX.DBModule;
using ZX.BLL.Extend;
using System.Collections;
using ZX.WebApp.cspModel;
using ZX.SYS.Library;
using OpenExpressApp;

using ZX.SYS.Bussiness.Phrase;
namespace ZX.WebApp.DesignForm
{
    public partial class TableData : ZX.Web.UI.Controls.BasePage
    {
        private static string _CodeSmithServiceURL;

        //public static string CodeSmithServiceURL
        //{
        //    get
        //    {
        //        if (_CodeSmithServiceURL == null)
        //        {
        //            _CodeSmithServiceURL = ConfigurationManager.AppSettings["CodeSmithServiceURL"];
        //        }
        //        return _CodeSmithServiceURL;
        //    }
        //}

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        /// <summary>
        /// 获取主表字段列表
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <returns>JSON格式字段列表</returns>
        [WebMethod]
        public static string GetMasterFieldList(string TableName) 
        {
            string strFieldList = "";
            if (!string.IsNullOrEmpty(TableName))
            {
                BaseBussnies bll = new BaseBussnies();
                IList<TableInfoStruc> list = bll.GetTableInfoStruc(TableName);//"DatPost"
                if (list != null)
                {
                    List<SysTableField> TFlist = new List<SysTableField>();
                    foreach (var entity in list)
                    {
                        SysTableField stf = new SysTableField();
                        stf.TableFieldID = Guid.NewGuid();
                        stf.TableID = Guid.NewGuid();
                        stf.TableName = entity.TableName;
                        stf.Is_PrimaryKey = entity.PKey;
                        stf.Is_Null = entity.CanNull;
                        stf.FieldName = entity.ColName;
                        stf.FiledType = entity.CType;
                        stf.Notes = entity.ColDesc;
                        stf.Length = entity.Length.ToString();
                        TFlist.Add(stf);
                    }
                    strFieldList = ZX.Common.Globals.ObjectToJSON(TFlist);
                }
            }
            return strFieldList;
        }
         
        //[WebMethod]
        //public static string GetCodeSmithServiceURL() { return CodeSmithServiceURL; }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string GetCodeSmithCompleteString(string formName, string masterTableName, string strJson, string colnum, string FormType)
        {
            string formString = "";
            if (!string.IsNullOrEmpty(masterTableName))
            {
                CodeCompleteString hs = new CodeCompleteString();
                formString = hs.CodeSmithCompleteString(formName, masterTableName, strJson, colnum, FormType);
            }
            return formString; 
        }


        /// <summary>
        /// 获取指定表名表是否存在
        /// </summary>
        /// <param name="TableName"></param>
        /// <returns></returns>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string IsTableExists(string TableName)
        {
            string isExists = "0";
            if (!string.IsNullOrEmpty(TableName))
            {
                
                DBTable dbTable = SqlDBTable.Instance;

                if (dbTable.IsTableExists(TableName)) { isExists = "1"; }
                else{isExists = "0";}
            }
            return isExists;
        }


        /// <summary>
        /// 获取表名
        /// </summary>
        [WebMethod]
        public static string GetTableNames()
        {
            string strTableList = "";
            SysCustomDefineForm df = new SysCustomDefineForm();
            IGTable it = df.getTableInfo();
            if (it.Count > 0)
            {
                System.Data.DataTable dt = it.GetTable;
                List<Dictionary> list = new List<Dictionary>();
               
                foreach (System.Data.DataRow row in dt.Rows)
                {
                     Dictionary d = new Dictionary();
                     string str = (string.IsNullOrEmpty(row["DisplayMember"].ToString())) ? "null" : row["DisplayMember"].ToString();

                     d.DisplayMember = row["DisplayMember"].ToString();
                      d.ValueMember=row["ValueMember"].ToString();
                      list.Add(d);
                }
             
                strTableList = ZX.Common.Globals.ObjectToJSON(list);
            }
            return strTableList;
        }

        /// <summary>
        /// 获取职等
        /// </summary>
        [WebMethod]
        public static string GetDatDutyLevel()
        {
            string strTableList = "";
            ZX.BLL.BDutyInfo df = new BLL.BDutyInfo();
            System.Data.DataTable dt = df.GetDatDutyLevel();
            if (dt.Rows.Count > 0)
            {
              
                List<Dictionary> list = new List<Dictionary>();

                foreach (System.Data.DataRow row in dt.Rows)
                {
                    Dictionary d = new Dictionary();
                    string str = (string.IsNullOrEmpty(row["Level"].ToString())) ? "null" : row["Level"].ToString();

                    d.DisplayMember = row["Level"].ToString();
                    d.ValueMember = row["Level"].ToString();
                    list.Add(d);
                }

                strTableList = ZX.Common.Globals.ObjectToJSON(list);
            }
            return strTableList;
        }

        /// <summary>
        /// 请假类型
        /// </summary>
        [WebMethod]
        public static string GetLeaveType()
        {
            string strTableList = "";
            BDatPhraseDetail pd = new BDatPhraseDetail();
            System.Data.DataTable dt = pd.GetLeaveType();
            if (dt.Rows.Count > 0)
            {

                List<Dictionary> list = new List<Dictionary>();

                foreach (System.Data.DataRow row in dt.Rows)
                {
                    Dictionary d = new Dictionary();
                    d.DisplayMember = row["DisplayMember"].ToString();
                    d.ValueMember = row["ValueMember"].ToString();
                    list.Add(d);
                }

                strTableList = ZX.Common.Globals.ObjectToJSON(list);
            }
            return strTableList;
        }

        #region 分司、部门、团队、岗位
        /// <summary>
        /// 获取组织架构
        /// </summary>
        /// <returns></returns>
         [WebMethod]
        public static string GetOrganize()
         {
           string strTableList = "";
           SysCustomDefineForm cdf=new SysCustomDefineForm();
           List<Dictionary> list = cdf.GetOrganizeAll();
           strTableList = ZX.Common.Globals.ObjectToJSON(list);
           return strTableList;
         }

        /// <summary>
        ///  获取指定部门的所有岗位
        /// </summary>
        /// <param name="DeptID"></param>
        /// <returns></returns>
         [WebMethod]
         public static string GetPost(string DeptID)
         {
             string strTableList = "";
             if (!string.IsNullOrEmpty(DeptID))
             {
                 Guid id = new Guid(DeptID);
                 SysCustomDefineForm cdf = new SysCustomDefineForm();
                 List<Dictionary> list = cdf.GetDepartmentByPost(id);
                 strTableList = ZX.Common.Globals.ObjectToJSON(list);
             }
             return strTableList;
         }
          
        #endregion
        /// <summary>
        /// 判断表单名是否存在
        /// </summary>
        [WebMethod]
        public static string GetIExistFormName(string formName)
        {
            string strmst = "";
            SysCustomDefineForm df = new SysCustomDefineForm();
            bool isexist = df.getIExistFormName(formName);
            if (isexist)
            { strmst = "1"; }
            else { strmst = "0"; }
            return strmst;
        }
         

        /// <summary>
        /// 获取字段数据源
        /// </summary>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string getFormFieldItems(string formID)
        {
            string strTableList = "";
            if (!string.IsNullOrEmpty(formID))
            {
                SysCustomDefineForm form = new SysCustomDefineForm();
                Guid _FormID = new Guid(formID);
                form = SysCustomDefineForm.Get(_FormID);
                if (form != null)
                {
                    IList<SysFieldItem> items = form.FieldItems.ToList<SysFieldItem>();

                    strTableList = ListToJson(items);
                }
           
            }
            return strTableList;
        }
        /// <summary>
        /// 下拉框变动时，置换表的字段
        /// </summary>
        [WebMethod]
        public static string getTableField(string TableName)
        {
            string strTableFieldList = "";
            if (!string.IsNullOrEmpty(TableName))
            {
                SysCustomDefineForm df = new SysCustomDefineForm();
                IGTable it = df.getTableField(TableName);
                if (it.Count > 0)
                {
                    strTableFieldList = ZX.Common.Globals.DataTableToCJson(it.GetTable);
                }
            }
            return strTableFieldList;
        }

        /// <summary>
        /// List转成json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string ListToJson<T>(IList<T> list)
        {
            System.Text.StringBuilder Json = new System.Text.StringBuilder();
            
            Json.Append("[");
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    System.Reflection.PropertyInfo[] pi = obj.GetType().GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pi.Length; j++)
                    {
                        if (pi[j].GetValue(list[i], null) != null)
                        {
                            Type type = pi[j].GetValue(list[i], null).GetType();
                            Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));

                            if (j < pi.Length - 1)
                            {
                                Json.Append(",");
                            }
                        }
                    }
                    Json.Append("}");
                    if (i < list.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]");
            return Json.ToString();
        }
        /// <summary>
        /// List转成json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonName"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string ListToJson<T>(IList<T> list, string jsonName)
        {
            System.Text.StringBuilder Json = new System.Text.StringBuilder();
            if (string.IsNullOrEmpty(jsonName))
                jsonName = list[0].GetType().Name;
            Json.Append("{\"" + jsonName + "\":[");
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    System.Reflection.PropertyInfo[] pi = obj.GetType().GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pi.Length; j++)
                    {
                        if (pi[j].GetValue(list[i], null) != null)
                        {
                            Type type = pi[j].GetValue(list[i], null).GetType();
                            Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));

                            if (j < pi.Length - 1)
                            {
                                Json.Append(",");
                            }
                        }
                    }
                    Json.Append("}");
                    if (i < list.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }

        /// <summary>
        /// 格式化字符型、日期型、布尔型
        /// </summary>
        /// <param name="str"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static string StringFormat(string str, Type type)
        {
            if (type != typeof(string))
            {
                str = "\"" + str + "\"";
            }
            else if ( string.IsNullOrEmpty(str))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(string))
            {
                str = String2Json(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime))
            {
                str = "\"" + str.Split(' ')[0] + "\"";
            }
            else if (type == typeof(bool))
            {
                str = "\"" + str.ToLower() + "\"";
            }
            else if (type == typeof(Guid))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(Int32))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(int))
            {
                str = "\"" + str + "\"";
            }

            return str;
        }
        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private static string String2Json(String s)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }


        /// <summary>
        ///字典字段
        /// </summary>
        [Serializable]
        public class CriteriaMember
        {


            public CriteriaMember() { }

            public string DisplayMember
            {
                get;
                set;
            }
           
            public string ValueMember
            {
                get;
                set;
            }
           
        }
    }
}